import datetime
import pytz

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.conf import settings

from basicinfo.models import Station, Personnel


class LabLog(models.Model):
    """
    机房日志信息
    """
    weather_type = (
        ('sunny', '晴'),
        ('cloudy', '多云'),
        ('overcast', '阴'),
        ('rain', '雨'),
        ('snowing', '雪'),
    )

    time_slot_choice = (
        (1, '上午'),
        (2, '下午'),
    )
    status_choice = (
        (1, '正常'),
        (2, '部分网络设备故障'),
        (3, '网络瘫痪'),
        (4, '其它'),
    )

    adding_way_choice = (
        (1, '自动添加'),
        (2, '自动添加/人工修改'),
        (3, '人工添加')
    )

    lab_template = models.FloatField(default=0.0, verbose_name='机房温度(°)')
    lab_humidity = models.FloatField(default=0.0, verbose_name='机房湿度(%RH)')

    hc_room_template = models.FloatField(default=0.0, verbose_name='人机交互室温度(°)')
    hc_room_humidity = models.FloatField(default=0.0, verbose_name='人机交互室湿度(%RH)')

    network_delay = models.IntegerField(default=15, verbose_name='网络延迟(ms)')
    packet_lose_rate = models.FloatField(default=0.0, verbose_name='信息节点掉包率(%)')

    time_slot = models.IntegerField(choices=time_slot_choice, verbose_name='记录时段')

    weather = models.CharField(max_length=6, choices=weather_type, default='sunny', verbose_name='天气情况')

    log_date = models.DateField(verbose_name='日志日期', default=timezone.now)

    log_time = models.TimeField(default=datetime.datetime.now(), verbose_name='记录时间点')

    adding_way = models.IntegerField(choices=adding_way_choice, verbose_name='添加方式')

    description = models.TextField(max_length=1000, blank=True, verbose_name='描述')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    last_updated = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')

    created_by = models.ForeignKey(User, null=True, on_delete=models.CASCADE, verbose_name='发布人',
                                   related_name='lablogs')
    updated_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='更新人',
                                   related_name='+')

    class Meta:
        verbose_name = '机房值班日志'
        verbose_name_plural = '机房值班日志'
        unique_together = ("log_date", "time_slot")

    @property
    def get_schedule(self):
        return ShiftSchedule.objects.get(duty_date=self.log_date)

    @property
    def is_overdue(self):
        log_datetime = datetime.datetime.combine(self.log_date, datetime.time(hour=0, minute=0, second=0),
                                                 tzinfo=pytz.timezone(settings.TIME_ZONE))
        if self.adding_way == 1:
            return timezone.now() - log_datetime > datetime.timedelta(hours=34)
        else:
            return timezone.now() - log_datetime > datetime.timedelta(hours=24)


class StationDataLog(models.Model):
    """
    小孔径台网五个子台数据连续率
    """
    station = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='datalogs', verbose_name='台站代码')
    log_date = models.DateField(verbose_name='日志日期')
    online_interrupt_start = models.DateTimeField(verbose_name='断记开始时间')
    online_interrupt_end = models.DateTimeField(verbose_name='断记恢复时间')
    online_interrupt_duration = models.FloatField(default=0.0, verbose_name='断记时长(s)')
    online_continuous_rate = models.FloatField(default=1.0, verbose_name='数据连续率')
    offline_is_download = models.BooleanField(default=False, verbose_name='离线数据是否已下载')
    offline_complete_rate = models.FloatField(default=100.0, verbose_name='离线数据完整率(%)')
    description = models.TextField(max_length=1000, blank=True, verbose_name='描述')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    last_updated = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')

    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='值班人', related_name='datalogs')
    updated_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='更新者',
                                   related_name='+')

    class Meta:
        verbose_name = '台站维护日志'
        verbose_name_plural = '台站维护日志'
        unique_together = ('station', 'log_date')

    @property
    def get_online_continuous_rate(self):
        return (60.0 * 60.0 * 24 * 1 - self.online_interrupt_duration) / (60.0 * 60.0 * 24 * 1) * 100.0


class StationCalibration(models.Model):
    """
    小孔径台网五个子台标定设置情况
    """
    station = models.ForeignKey(Station, on_delete=models.CASCADE, verbose_name='所属台站')
    trigger_time = models.DateTimeField(verbose_name='标定触发时间')


class StationCalibrationLog(models.Model):
    """
    小孔径台网五个子台标定日志
    """
    station = models.ForeignKey(Station, on_delete=models.CASCADE, verbose_name='所属台站')
    status = models.BooleanField(default=False, verbose_name='标定状态')

    is_cut = models.BooleanField(default=False, verbose_name='是否截取')

    is_manual_trigger = models.BooleanField(default=False, verbose_name='是否手动触发')
    manual_trigger_time = models.DateTimeField(verbose_name='标定手动触发时间')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    last_updated = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')

    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='值班人', related_name='calibrationlogs')
    updated_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='更新者',
                                   related_name='+')

    description = models.TextField(max_length=1000, blank=True, verbose_name='描述')


class StationMaintenanceLog(models.Model):
    """
    小孔径台网五个子台现场维护日志
    """
    station = models.ForeignKey(Station, on_delete=models.CASCADE, verbose_name='所属台站', related_name='maintenancelogs')
    maintenance_date = models.DateField(verbose_name='维护日期')
    maintainer = models.ManyToManyField(Personnel, verbose_name='维护人', related_name='maintenances')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    last_updated = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')

    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='发布人', related_name='maintenancelogs')
    updated_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='更新者',
                                   related_name='opmaintenancelogs')
    description = models.TextField(max_length=1000, blank=True, verbose_name='描述')

    class Meta:
        verbose_name = '台站维护日志'
        verbose_name_plural = '台站维护日志'

    def __str__(self):
        return "{}({})维护记录".format(self.station, self.maintenance_date)


class ShiftSchedule(models.Model):
    """
    排班表
    """
    duty_date = models.DateField(unique=True, verbose_name='值班日期')
    arrange_duty_person = models.ForeignKey(Personnel, null=True, on_delete=models.SET_NULL, verbose_name='安排值班人',
                                            related_name='+')
    actual_duty_person = models.ForeignKey(Personnel, null=True, on_delete=models.SET_NULL, verbose_name='真实值班人',
                                           related_name='schedules')

    @property
    def is_today(self):
        return datetime.date.today() == self.duty_date

    @property
    def is_past_due(self):
        return datetime.date.today() > self.duty_date

    @property
    def is_future(self):
        return datetime.date.today() < self.duty_date

    @property
    def is_arrangement(self):
        return self.arrange_duty_person.pk == self.actual_duty_person.pk
